// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './taskAddStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from 'moment';
import Track from 'widget/Map/Track'
import { Grid, QueryCondition } from 'widget/Grid'

const FormItem = Form.Item
const { RangePicker } = DatePicker

const formItemLayoutPro = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const formItemLayoutForTime = {
  labelCol: { span: 2 },
  wrapperCol: { span: 20 },
};
const imageLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}

function timestampToTime(timestamp) {
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    return Y+M+D+h+m+s;
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const taskAddView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {methodList,memberList,selectedRows,selectedRowKeys,teamModal,loading,userList,mapList,Mapmodel,query, actionType, btnLoading ,products,areaList} = modelObj
  query.createrId = localStorage.getItem('username')

  if(query.startTime){
    query.startTime = timestampToTime(query.startTime)
  }
  if(query.endTime){
    query.endTime = timestampToTime(query.endTime)
  }
  //地图
  // let mapQueryList = [
  //   { name: '省市', type: 'cascader', list: mapList, key: 'code', value: '' }
  // ];
  // 表格配置------------开始
  const columns = [
    {
      title: '编号', dataIndex: 'no', key: 'no', width: 200,
      render: function (value, item, index) {
            return index+1
      }
    }, 
    {
      title: '用户名', dataIndex: 'name', key: 'name', width: 200,
      render: function (value, item, index) {
        return item.name
      }
    },
    {
      title: '头像', dataIndex: 'photo', key: 'photo', width: 200,
      render: function (value, item, index) {
        return <div>
          <img style={{width:'66px',height:'66px'}} src={item.photo} alt=""/>
        </div>
      }
    }
  ]
  const columns1 = [
    {
      title: '编号', dataIndex: 'no', key: 'no', width: 200,
      render: function (value, item, index) {
            return index+1
      }
    }, 
    {
      title: '用户名', dataIndex: 'name', key: 'name', width: 200,
      render: function (value, item, index) {
        return item.name
      }
    },
    {
      title: '头像', dataIndex: 'photo', key: 'photo', width: 200,
      render: function (value, item, index) {
        return <div>
          <img style={{width:'66px',height:'66px'}} src={item.photo} alt=""/>
        </div>
      }
    }
  ]

  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: columns,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: memberList},
    },
    scroll: { x: 1200 },
    paginationFlag : false,
    loading
  }

  const gridProps1 = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange',
    data: {
      columns: columns1,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: userList},
      selectedRowKeys,
    },
    scroll: { x: 800 },
    paginationFlag : false,
    loading
  }

  //过滤项目数据
  function filterProjectList(areaId){
    products = []
    let list = []
    for(var item of areaList){
      if(item.value == areaId){
        list = item.children
      }
    }
    if(list.length){
      products =  list.map((item,index)=>{
        return {
          label: item.buname,
          value: item.buguid,
        }
      })
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {products}
    })
  }

  //区域改变时
  function inputAreaChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    filterProjectList(value)
    dispatch({
      type: `${namespace}/getmMethod`,
      payload: {value}
    })
  }
  //项目改变时
  function projectChange(value, name){
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    dispatch({
      type: `${namespace}/showUse`,
      payload: {value}
    })
  }

  function goback(){
    hashHistory.push({
      pathname: '/home/expandManage/taskList',
      query: {}
    });
  }
  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
  }

  
  function updateMapmodel(status) {
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { Mapmodel: status }
    });
  }
 
 //新增拓客方式弹窗
 function updateTeam(){
  teamModal.visible = !teamModal.visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { teamModal}
    })
  }
  function teamSubmit(){
    memberList  = selectedRows
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { memberList }
    })
    updateTeam()
  }
  //日期改变时
  function dateChange(m,s){
  dispatch({
      type: `${namespace}/updateStore`,
      payload: {
          query: {
              ...query,
              startTime: s[0],
              endTime: s[1],
          }
      }
    })
  }
  //弹出框回调
  function cbk( latAndLon,mapAddress) {
    query.addressName = mapAddress
    query.latAndLon = latAndLon
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { query }
    });
    form.resetFields(['addressName'])
  }

  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {},
          callback:()=>{
            hashHistory.push({
              pathname: '/home/expandManage/taskList',
              query: {areaId:query.areaId,projectId:query.projectId}
            })
          }
        })
      }
    })
  }

  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button type='primary' onClick={e => submit()} loading={btnLoading}>保存</Button>
        <Popconfirm placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => goback()} okText="确定" cancelText="取消">
          <Button>关闭</Button>
        </Popconfirm>
      </div>

      <CollapsiblePanels title="任务信息" hideUpDownBtn={true} >
        <Row>
          <Col span={8}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择区域'
                }],
                initialValue: query.areaId
              })(
                <Select  placeholder='请选择区域' onChange={(e) => { inputAreaChange(e, 'areaId') }}>
                  {areaList == undefined ?null:areaList.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='项目'  {...formItemLayoutPro}>
              {getFieldDecorator('projectId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择项目'
                }],
                initialValue: query.projectId
              })(
                <Select  placeholder='请选择项目' onChange={(e) => { projectChange(e, 'projectId') }}>
                  <Select.Option value="0">请选择</Select.Option>
                  {products == undefined ?null:products.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='渠道'  {...formItemLayoutPro}>
              {getFieldDecorator('channel', {
                rules: [{
                  required: true, whitespace: true, message: '请选择渠道'
                }],
                initialValue: query.channel
              })(
                <Select  placeholder='请选择渠道' onChange={(e) => { inputChange(e, 'channel') }}>
                  <Select.Option value="行销自拓">行销自拓</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='任务名称'  {...formItemLayoutPro}>
              {getFieldDecorator('taskName', {
                rules: [{
                  required: true, whitespace: true, message: '请输入任务名称'
                }],
                initialValue: query.taskName
              })(
                <Input  placeholder='请输入任务名称' onChange={(e) => { inputChange(e.target.value, 'taskName') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
            <Col className="col" span={24}>
              <FormItem {...imageLayout}
                label="任务地址">
                {getFieldDecorator('addressName', {
                  rules: [{required: true,whitespace: true, message: '请输入任务地址'}],
                  initialValue: query.addressName
                })(
                <Row style={{ border: 0 }}>
                  {/* <Col span={20}><Input placeholder='任务地址' onChange={(e) => { inputChange(e.target.value, 'addressName') }} /></Col> */}
                  <Col span={2}><a onClick={(e) => { updateMapmodel(true) }}>选择</a></Col>
                  <Col span={20}><span>{query.addressName}</span></Col>
                </Row>
                )}
              </FormItem>
            </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='拓客任务量'  {...formItemLayoutPro}>
              {getFieldDecorator('target', {
                rules: [{
                  required: true, whitespace: true, message: '请输入拓客任务量'
                }],
                initialValue: query.target
              })(
                <Input  placeholder='请输入拓客任务量' onChange={(e) => { inputChange(e.target.value, 'target') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='任务发布人'  {...formItemLayoutPro}>
              {getFieldDecorator('createrName', {
                rules: [{
                  required: false, whitespace: true, message: '请输入任务发布人'
                }],
                initialValue: query.createrName
              })(
                // <Input  placeholder='发布人' onChange={(e) => { inputChange(e.target.value, 'createrName') }} />
                <span>{query.createrName}</span>
              )}
            </FormItem>
          </Col>
        </Row>
        <FormItem
          {...formItemLayoutForTime}
          label="生效时间"
        >
          {getFieldDecorator('Times', {
            rules: [{ required: true, message: '请选择生效时间' },
            ],
            initialValue: query.startTime ? [moment(query.startTime, 'YYYY-MM-DD HH:mm:ss'), moment(query.endTime, 'YYYY-MM-DD HH:mm:ss')] : [],
          })(
            <RangePicker  showTime={{
              hideDisabledOptions: true,
              defaultValue: [moment(null, 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],

            }}
              format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateString) => { dateChange(date, dateString) }}
            />
          )}
        </FormItem>
        <Row>
          <Col span={8}>
            <FormItem label='拓客方式'  {...formItemLayoutPro}>
              {getFieldDecorator('method', {
                rules: [{
                  required: true, whitespace: true, message: '请输入拓客方式'
                }],
                initialValue: query.method 
              })(
                <Select  placeholder='请选择拓客方式' onChange={(e) => { inputChange(e, 'method') }}>
                   {methodList == undefined ?null:methodList.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{padding: '0 26px'}}>
            <span>添加成员 :</span>
            <div style={{padding: '0 66px'}}>
              <div className="details-but" style={{marginBottom: '6px'}}>
                  <Button  onClick={() => updateTeam()}>添加成员</Button>
              </div>
              <div className="detailsTab">
                  <Grid {...gridProps} />
              </div>
            </div>
        </div>
      </CollapsiblePanels>
      <Track
        visible={Mapmodel}
        // queryList={mapQueryList}
        btnDiv={true}
        latAndLon={query.latAndLon}
        cancal={e => updateMapmodel(false)}
        cbk={(v, b) => cbk(v, b)}
        options={mapList}
      />
      <Modal
          title="信息"
          visible={teamModal.visible}
          width='1000px'
          destroyOnClose={true}
          onOk={() => { teamSubmit() }}
          onCancel={() => { updateTeam() }}
        >
        <div>
          <Grid {...gridProps1} />
        </div>    
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(taskAddView))